package com.ccys.netty.service.impl;

import com.ccys.netty.Dto.NettyPushMessageBody;
import com.ccys.netty.config.NettyConfig;
import com.ccys.netty.content.BaseConstant;
import com.ccys.netty.service.PushService;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.group.ChannelGroupFuture;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author sixiaojie
 * @date 2020-03-30-20:10
 */
@Service
public class PushServiceImpl implements PushService {
    @Autowired
    private RedisTemplate redisTemplate;



    @Override
    public void sendMessageWebSocket(String objId, String msg){
        ConcurrentHashMap<String, ChannelHandlerContext> userChannelMap = NettyConfig.getUserChannelMap();
        ChannelHandlerContext channel = userChannelMap.get(objId);
        if(!Objects.isNull(channel)){
            //测试客户端需要这样写才能收到消息
            channel.writeAndFlush(new TextWebSocketFrame(msg));

        }else {
            // 发布，给其他服务器消费
            NettyPushMessageBody pushMessageBody = new NettyPushMessageBody();
            pushMessageBody.setUserId(objId);
            pushMessageBody.setMessage(msg);
            //将消息发送到 redis订阅topic
            redisTemplate.convertAndSend(BaseConstant.PUSH_MESSAGE_TO_ONE,pushMessageBody);
        }


    }
    @Override
    public void sendMessageAllWebSocket(String msg){
        // 发布，给其他服务器消费
        redisTemplate.convertAndSend(BaseConstant.PUSH_MESSAGE_TO_ALL,msg);
        //此处不需要写发送消息 服务器监听到订阅主题后会自动发送消息
        //ChannelGroupFuture channelFutures = NettyConfig.getChannelGroup().writeAndFlush(new TextWebSocketFrame(msg));
    }


    //TODO 集群环境下 给一个ID 怎么知道通道在那一台服务器上是可以用的，如果不能使用 需要告知的需求？？
}
